/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: TokenAuthenticationFilter
 * @Package com.rx.core.filter
 * @Description: 上下文获取token
 * @author: 陈锦韬
 * @date: 2021\6\24 0024
 * @version V1.0
 * @Copyright: 2021 陈锦韬  All rights reserved.
 */
package com.rx.core.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rx.core.base.RxBaseConstant;
import com.rx.core.base.RxResponse;
import com.rx.core.bean.LoginUserInfo;
import com.rx.core.bean.RxConfigBean;
import com.rx.core.enm.RX_ENABLE;
import com.rx.core.enm.RX_LOG_MODE;
import com.rx.core.util.EmptyChecker;
import com.rx.core.util.RxContentHolder;
import com.rx.core.util.RxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Administrator
 * @Description: 上下文获取token
 * @date: 2021\6\24 0024
 */
@Component
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    /**
     * 开关配置
     */
    @Autowired
    private RxConfigBean rxConfigBean;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try{

            // 解析头中的token
            String token = request.getHeader(RxBaseConstant.HEARER_JSON_TOKEN);
            if (EmptyChecker.isEmpty(token)){

                if (!RX_ENABLE.isEnable(rxConfigBean.getRxNeedJsonToken())){
                    filterChain.doFilter(request,response);
                    return;
                }
                // 无权限信息
                RxResponse.response(response,"您无权访问");
                return;
            }
            log.info(RX_LOG_MODE.DEFAULT.getFormat(),"授权上下文过滤器");
            String json = RxUtil.EncryptUtil.decodeUTF8StringBase64(token);
            JSONObject parse = JSON.parseObject(json);
            String userJson = parse.getString("principal");
            LoginUserInfo principal = JSON.parseObject(userJson,LoginUserInfo.class);
            RxContentHolder.getContext().setUserInfo(principal);
            log.info(RX_LOG_MODE.DEFAULT.getFormat("{}"),"用户信息",principal);
            if (EmptyChecker.notEmpty(filterChain)){
                filterChain.doFilter(request,response);
            }

        }finally {
            RxContentHolder.clearContext();
        }
    }
}
